package api.utils;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;

import javax.activation.FileDataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class EmailUtils {

	public static void main(String[] args) {
		try {
			//sendMsg();
			String path= "E:\\workspace\\apitest0407\\data\\登录_result_2022-05-05(21_43).xlsx";
			String path2= "E:\\workspace\\apitest0407\\data\\空_result_2022-05-05(21_43).xlsx";
			List<String> list =new ArrayList<>();
			list.add(path);
			list.add(path2);
			 sendEmailsWithAttachments("测试结果","请查收",list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void sendEmailsWithAttachments(String title, String context, List<String> filepath)
			throws EmailException {

		String hostname = PropertiesUtils.getString("mail.host");
		String password = PropertiesUtils.getString("mail.password");
		String username = PropertiesUtils.getString("mail.username");
		String[] toList = PropertiesUtils.getStringArray("mail.touser");

		// Create the email message
		BevisHtmlEmail email = new BevisHtmlEmail();
		email.setHostName(hostname); // 邮件服务器域名
		email.setAuthentication(username, password); // 邮箱账户
		email.setCharset("UTF-8"); // 邮件的字符集

		email.setSubject(title);
		email.setFrom(username); // 发件人地址
		email.setHtmlMsg(context);

		for (String to : toList) {
			email.addTo(to); // 收件人地址，可以设置多个
		}
		// add the attachment
		for (String fp : filepath) {
			File file = new File(fp);
			FileDataSource fds = new FileDataSource(file);
			email.attach(fds,file.getName(),"测试文件",EmailAttachment.ATTACHMENT);
		}
		// send the email
		email.send();
	}

}
